package cn.wxz1997.permission.service.impl;

import cn.wxz1997.permission.dao.RoleMapper;
import cn.wxz1997.permission.dao.RolePermissionMapper;
import cn.wxz1997.permission.dao.RoleUserMapper;
import cn.wxz1997.permission.dto.RoleForm;
import cn.wxz1997.permission.model.Role;
import cn.wxz1997.permission.pojo.RolePermission;
import cn.wxz1997.permission.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description: ${todo}
 * @Author: wxz1997
 * @Date 18-9-2下午2:52
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public Role add(RoleForm roleForm) {
        Role role = modelMapper.map(roleForm, Role.class);
        role.setCreateTime(new Date());
        roleMapper.insertSelective(role);
        List<Integer> permissionIds = roleForm.getPermissionIds();
        if(null != permissionIds){
            for (Integer permissionId : permissionIds){
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(role.getId());
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insertSelective(rolePermission);
            }
        }
        return roleMapper.selectByPrimaryKey(role.getId());
    }

    /**
     * 更新权限时先删后插入
     * @param roleForm
     * @return
     */
    @Override
    public Role update(RoleForm roleForm) {
        Role role = modelMapper.map(roleForm, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        List<Integer> permissionIds = roleForm.getPermissionIds();
        rolePermissionMapper.deleteByRoleId(role.getId());
        log.info("roleId:" + role.getId());
        if(null != permissionIds){
            for (Integer permissionId : permissionIds){
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(role.getId());
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insertSelective(rolePermission);
            }
        }

        return roleMapper.selectByPrimaryKey(role.getId());
    }

    @Override
    public Integer delete(Integer id) {
        roleUserMapper.deleteByRoleId(id);
        rolePermissionMapper.deleteByRoleId(id);
        return roleMapper.deleteByPrimaryKey(id);
    }
}
